package cn.edu.baiyunu.myapplication.ui.history

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import cn.edu.baiyunu.myapplication.data.db.entity.PhotoRecord
import cn.edu.baiyunu.myapplication.data.repository.PhotoRepository
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 历史页面ViewModel
 */
class HistoryViewModel(private val photoRepository: PhotoRepository) : ViewModel() {

    // 搜索关键词
    private val _searchQuery = MutableStateFlow("")
    val searchQuery = _searchQuery

    // 当前选择的排序方式
    private val _sortOrder = MutableStateFlow(SortOrder.DATE_DESC)
    val sortOrder = _sortOrder

    // 当前选择的筛选规格
    private val _selectedSpecType = MutableStateFlow<String?>(null)
    val selectedSpecType = _selectedSpecType

    // 是否显示搜索栏
    private val _isSearchVisible = MutableLiveData(false)
    val isSearchVisible: LiveData<Boolean> = _isSearchVisible

    // 操作状态提示
    private val _statusMessage = MutableLiveData<String?>(null)
    val statusMessage: LiveData<String?> = _statusMessage

    // 排序方式枚举
    enum class SortOrder {
        DATE_DESC, DATE_ASC, SIZE_DESC, SIZE_ASC
    }

    // 照片记录，合并搜索、排序和筛选条件
    @OptIn(ExperimentalCoroutinesApi::class)
    val photoRecords = combine(
        _searchQuery,
        _sortOrder,
        _selectedSpecType
    ) { query, order, specType ->
        Triple(query, order, specType)
    }.flatMapLatest { (query, order, specType) ->
        // 首先获取原始数据流
        val baseFlow = when {
            // 如果有筛选规格
            specType != null -> photoRepository.getPhotoRecordsBySpecType(specType)
            // 如果有搜索查询
            query.isNotEmpty() -> photoRepository.searchPhotoRecords(query)
            // 否则获取所有照片
            else -> photoRepository.getAllPhotoRecords()
        }

        // 排序处理在UI层进行，因为Room的Flow无法在此处排序
        baseFlow
    }.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = emptyList()
    ).asLiveData()

    /**
     * 设置搜索关键词
     */
    fun setSearchQuery(query: String) {
        _searchQuery.value = query
    }

    /**
     * 切换搜索栏显示状态
     */
    fun toggleSearchVisibility() {
        _isSearchVisible.value = !(_isSearchVisible.value ?: false)
        // 当隐藏搜索栏时，清空搜索内容
        if (_isSearchVisible.value == false) {
            setSearchQuery("")
        }
    }

    /**
     * 设置搜索栏显示状态
     */
    fun setSearchVisible(visible: Boolean) {
        _isSearchVisible.value = visible
        // 当隐藏搜索栏时，清空搜索内容
        if (!visible) {
            setSearchQuery("")
        }
    }

    /**
     * 更新搜索查询（用于新版本API）
     */
    fun updateSearchQuery(query: String) {
        _searchQuery.value = query
    }

    /**
     * 切换排序方式
     */
    fun toggleSortOrder() {
        _sortOrder.value = when (_sortOrder.value) {
            SortOrder.DATE_DESC -> SortOrder.DATE_ASC
            SortOrder.DATE_ASC -> SortOrder.SIZE_DESC
            SortOrder.SIZE_DESC -> SortOrder.SIZE_ASC
            SortOrder.SIZE_ASC -> SortOrder.DATE_DESC
        }
    }

    /**
     * 设置排序方式
     */
    fun setSortOrder(order: SortOrder) {
        _sortOrder.value = order
    }

    /**
     * 设置筛选规格
     */
    fun setSelectedSpecType(specType: String?) {
        _selectedSpecType.value = specType
    }

    /**
     * 删除单个照片记录
     */
    fun deletePhotoRecord(id: Long) {
        viewModelScope.launch {
            try {
                photoRepository.deletePhotoRecord(id)
                _statusMessage.value = "已删除照片"
            } catch (e: Exception) {
                _statusMessage.value = "删除失败: ${e.message}"
            }
        }
    }

    /**
     * 清除所有照片记录
     */
    fun clearAllPhotoRecords() {
        viewModelScope.launch {
            try {
                photoRepository.deleteAllPhotoRecords()
                _statusMessage.value = "已清空所有照片记录"
            } catch (e: Exception) {
                _statusMessage.value = "清空失败: ${e.message}"
            }
        }
    }

    /**
     * 清除状态消息
     */
    fun clearStatusMessage() {
        _statusMessage.value = null
    }

    /**
     * 获取格式化的创建时间
     */
    fun getFormattedDate(timestamp: Long): String {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
        return dateFormat.format(Date(timestamp))
    }

    /**
     * 获取分组后的照片列表
     */
    fun getGroupedPhotoRecords(photos: List<PhotoRecord>): Map<String, List<PhotoRecord>> {
        // 定义日期格式化器，只保留日期部分
        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        
        // 排序处理
        val sortedList = when (_sortOrder.value) {
            SortOrder.DATE_DESC -> photos.sortedByDescending { it.createdAt }
            SortOrder.DATE_ASC -> photos.sortedBy { it.createdAt }
            SortOrder.SIZE_DESC -> photos.sortedByDescending { it.width * it.height }
            SortOrder.SIZE_ASC -> photos.sortedBy { it.width * it.height }
        }
        
        // 按日期分组
        return sortedList.groupBy {
            val date = Date(it.createdAt)
            dateFormat.format(date)
        }
    }
} 